﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using Microsoft.Practices.Composite.Presentation.Commands;
using System.Windows;

namespace Common.UI.EM.Agregation
{
    public class GenericAgregationPresenter<E>
        where E : EntityObject, new()
    {

        public AgregationView<E> View { get; set; }

        
        /// <summary>
        /// A usar como binding
        /// </summary>
        public E NewEntity { get; set; }


        public DelegateCommand<Object> AddCommand
        {
            get;
            set;
        }

        public DelegateCommand<Object> DeleteCommand
        {
            get;
            set;
        }

        public GenericAgregationPresenter(AgregationView<E> view)
        {
            this.View = view;

            this.AddCommands();

            this.InitializePresenter();
        }

        private void InitializePresenter()
        {
            NewEntity = new E();
        }


        private void AddCommands()
        {
            this.AddCommand = new DelegateCommand<object>(ExecuteAddCommand, CanExecuteAddCommand);
            this.DeleteCommand = new DelegateCommand<object>(ExecuteDeleteCommand, CanExecuteDeleteCommand);
        }


        private void ExecuteDeleteCommand(Object arg)
        {
            if (this.View.GetSelectedEntity() != null && this.ValidateOnDelete() && this.View.ValidateDeleteEntity((E)this.View.GetSelectedEntity()))
            {
                this.DeleteEntity();
            }
        }

        protected virtual bool ValidateOnDelete()
        {
            if (MessageBox.Show("¿Está seguro que desea eliminar permanentemente el registro?", "Confirmación", MessageBoxButton.YesNo) == MessageBoxResult.No)
            {
                return false;
            }
            return true;
        }

        private Boolean CanExecuteDeleteCommand(Object arg)
        {
            return true;
        }

        private void DeleteEntity()
        {
            this.View.List.Remove((E)this.View.GetSelectedEntity());
        }


        private void ExecuteAddCommand(Object arg)
        {
            if (this.View.ValidateNewEntity(this.NewEntity))
            {
                this.AddEntity();
            }
        }

        private Boolean CanExecuteAddCommand(Object arg)
        {
            return true;
        }

        private void AddEntity()
        {
            if (this.View.List == null)
            {
                this.View.List = new EntityCollection<E>();
            }
            this.View.List.Add(this.NewEntity);

            this.NewEntity = new E();

            this.View.UpdateListView();

        }

    }
}
